<template>
	<div>
		<div class="app-container">
			<TopInfo />
			<Search :lookup="data.lookup" @investigate="inves" />
			<el-button v-prmis="'machine_add'" :disabled="unAuth" type="primary" size="small" @click="add()">
				<template #default>
					<span class="text-sm">{{ $t('machine.add') }}</span>
				</template>
			</el-button>
			<el-button v-prmis="'machine_export'" type="primary" size="small" @click="getExport">
				<template #default>
					<span class="text-sm">{{ $t('machine.ExportDevice') }}</span>
				</template>
			</el-button>
			<el-button type="primary" size="small" @click="control(1, '休眠设置')">
				<template #default>
					<span class="text-sm">{{ $t('machine.dormancyAll') }}</span>
				</template>
			</el-button>
			<el-button type="primary" size="small" @click="control(2, '唤醒设置')">
				<template #default>
					<span class="text-sm">{{ $t('machine.awakenAll') }}</span>
				</template>
			</el-button>
			<div class="btn float-right relative">
				<el-form-item prop="m_id" class=" mr-12 z-10">
					<el-input v-model="data.machineValue" @input="inputVal"
						:placeholder="$t('machine.enterMachineCode')" />
				</el-form-item>
				<el-button class="absolute right-0 top-0" size="small" @click="goTo()" :disabled="isGoTo">
					<span class="text-sm">{{ $t('public.go') }}</span>
				</el-button>
			</div>
		</div>
		<div class="app-container" v-loading="data.mtloading">
			<div class="text-center" v-if="unAuth">
				{{ unAuth }}
			</div>
			<div v-else v-for="item of data.list" :key="item.m_id">
				<listinfo :item="item" @onstatus="onstatus" @onmacbtn="onmacbtn" />
			</div>
			<PageNum :total="data.total" :page="data.machines" @exposeData="current" @fraction="fraction" />
		</div>
		<el-dialog v-model="data.macstatus" :title="$t('machine.settings')" center width="40%"
			:close-on-click-modal="false" @close="closeDialog">
			<el-form v-loading="data.dlloading" :model="data.machine" :inline="true" label-width="140">
				<el-form-item :label="$t('machine.code') + ':'" prop="selectlist" class="w-10/12">
					<el-select v-model="data.selectlist" multiple filterable :placeholder="$t('message.pleaseSelect')">
						<el-option v-for="item in data.maclist" :key="item.machine_id"
							:label="item.m_id + ' - ' + item.machine_id + ' (' + item.machine_name + ')'"
							:value="item.machine_id" />
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('machine.function') + ':'" prop="machine_id" class="w-10/12">
					<el-input v-model="data.title" :placeholder="$t('message.pleaseEnter')" readonly />
				</el-form-item>
				<el-form-item :label="$t('machine.executionTime') + ':'" prop="machine_id" class="w-10/12">
					<el-select v-model="data.time">
						<el-option :label="$t('machine.executeImmediately')" :value="1" />
						<el-option v-if="data.machine.msgType <= 5" :label="$t('machine.timedExecution')" :value="2" />
					</el-select>
				</el-form-item>
				<el-form-item v-if="data.time == 2" :label="$t('date.time') + ':'" prop="machine_id" class="w-10/12">
					<el-date-picker v-model="data.machine.time_point" :disabled-date="disabledDate" type="datetime"
						:placeholder="$t('message.pleaseSelect')" format="YYYY/MM/DD HH:mm:ss" value-format="x"
						style="width: 100%;" />
				</el-form-item>
				<div class="w-full text-center">
					<div class="inline-block">
						<el-button type="primary" size="small" @click="submit()">
							<template #default>
								<span class="text-sm">{{ $t('public.save') }}</span>
							</template>
						</el-button>

						<el-button size="small" @click="data.macstatus = false">
							<template #default>
								<span class="text-sm">{{ $t('public.cancel') }}</span>
							</template>
						</el-button>
					</div>
				</div>

			</el-form>
		</el-dialog>
		<exports :dialogVisible="dialogExport" @close="dialogExport = false" />
	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import TopInfo from '@/components/TopInfo/index.vue';
import Search from '@/components/Search/index.vue';
import PageNum from '@/components/PageNum/index.vue';
import listinfo from '../common/list_info.vue';
import { getgroupList } from '@/api/machine_type';
import { getmachineList, delmachine, updatemachine, exportMachine, sendAllControl } from '@/api/machine';
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import exports from '@/components/export.vue';
import level from '@/utils/level';
import { close } from 'fs';
const dialogExport = ref(false)
let isGoTo = ref(true)
const router = useRouter()
const route = useRoute()
let unAuth = ref()
let data = reactive({
	title: '', // 弹窗标题
	time: 1, // 执行时间
	macstatus: false, // 弹窗
	machine: { // 
		machine_id: '',
		msgType: 0,
		time_point: '',
	},
	maclist: [],
	selectlist: [],
	machineValue: '',
	mtloading: true, // 加载
	dlloading: false, // 弹窗加载
	lookup: [ // 筛选栏
		{ title: $t('machine.code'), type: 'mId', value: '', key: 'm_id' },
		{ title: $t('machine.name'), type: 'input', value: '', key: 'machine_name' },
		{ title: $t('machine.group'), type: 'linkages', select: [], props: {}, value: '', key: 'machine_group_id', strictly: true },
		{
			title: $t('machine.machineStatus'), type: 'define', select: [
				{ label: $t('public.normal'), value: 1 },
				{ label: $t('public.disable'), value: 2 },
				{ label: $t('public.uphold'), value: 3 },
			], value: '', key: 'status'
		},
		{
			title: $t('public.Offline'), type: 'define', select: [
				{ label: $t('public.onLine'), value: 1 },
				{ label: $t('public.offline'), value: 2 },
			], value: '', key: 'online'
		},
		{
			title: $t('machine.appType'), type: 'define', select: [
				{ label: $t('machine.vending'), value: 1 },
				{ label: $t('machine.store'), value: 2 },
			], value: '', key: 'device_type'
		},
		{ title: $t('machine.software.softwareVer'), type: 'input', value: '', key: 'version' }
	],
	list: [], // 列表信息
	machines: { // 筛选数据
		page: 1,
		pageNum: 15
	},
	total: 0, // 总条数
})
const propsss = reactive(
	{
		checkStrictly: true,
		lazy: true,
		async lazyLoad(node: any, resolve: any) {
			const { level, value } = node
			let nodes = await getgroupList({ pid: value });
			if (nodes.state == 100 || nodes.state == 300) {
				resolve([]);
			}
			const nodesa = nodes.data.map((item) => ({
				value: item.mg_id,
				label: item.mg_id + '-' + item.mg_name
			}))
			resolve(nodesa);
		}
	}
)
data.lookup[2].props = propsss
if (route.query.online) {
	data.lookup.forEach(item => {
		let id = Number(route.query.online)
		if (item.key == 'online') {
			item.value = id
			data.machines.online = id
		}
	})
}
if (route.query.status) {
	data.lookup.forEach(item => {
		let id = Number(route.query.status)
		if (item.key == 'status') {
			item.value = id
			data.machines.status = id
		}
	})
}
// 监听路由变化
watchEffect(() => {
	if (!route.query.online) {
		data.lookup.forEach(item => {
			if (item.key == 'online') {
				item.value = ''
			}
		})
	}
	if (!route.query.status) {
		data.lookup.forEach(item => {
			if (item.key == 'status') {
				item.value = ''
			}
		})
	}
});
// 批量控制设备
let control = (e, title) => {
	data.title = title
	data.machine.msgType = e
	data.macstatus = true
}
let closeDialog = () => {
	data.macstatus = false
	data.selectlist = []
	data.machine.time_point = ''
	data.time = 1
}
// 数据提交
let submit = () => {
	data.dlloading = true
	let info = {
		machine_id: data.selectlist.join(','),
		msgType: data.machine.msgType,
	}
	if (data.time == 2) {
		if (data.machine.time_point == '' || data.machine.time_point == null) {
			ElMessage({
				message: $t('message.pleaseTime'),
				type: 'error'
			})
			return
		} else {
			info.time_point = level.gettime(data.machine.time_point, 3)
		}
	}
	sendAllControl(info).then(res => {
		data.dlloading = false
		if (res.state == 200) {
			ElMessage({
				message: $t('message.setSuccess'),
				type: 'success'
			})
			data.macstatus = false
			data.selectlist = []
			data.machine.time_point = ''
			data.time = 1
			return
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	}).catch(err => {
		data.dlloading = false
		ElMessage({
			message: err.msg,
			type: 'error'
		})
	})
}

// 导出
let getExport = () => {
	ElMessageBox.confirm($t('message.isExport')).then(res => {
		exportMachine(data.machines).then(res => {
			if (res.state == 200) {
				dialogExport.value = true
				getmachines()
				return
			}
			ElMessage({
				message: $t('message.networkFailed'),
				type: 'error'
			})
		}).catch(err => {
			console.log(err)
		})
	}).catch(err => {
		console.log('取消')
	})
}
let inputVal = () => {
	if (data.machineValue) {
		isGoTo.value = false
	} else {
		isGoTo.value = true
	}
}
// 获取设备列表
let getList = () => {
	getmachineList().then(res => {
		console.log(res, 'res')
		if (res.state == 200) {
			data.maclist = res.data
		}
	})
}
getList()
let goTo = () => {
	let obj = {
		id: ''
	}
	for (let item of data.maclist) {
		if (item.machine_id == data.machineValue) {
			obj.id = item.m_id
		}
	}
	if (obj.id == '') {
		ElMessage({
			message: $t('message.unInfo'),
			type: 'error'
		})
		return
	}
	let query = {
		l: encodeURI(JSON.stringify({
			id: obj.id,
			type: 'overview'
		}))
	}
	router.push({ path: '/machine/info/details_info', query: query })
}
// 检测是否从哪里过来
let gethomeurl = () => {
	let query = route.query
	if (query.l == undefined) {
		getmachines()
		return
	}

	let l = JSON.parse(decodeURI(query.l))
	let info = ''
	if (l.homeurl != undefined) {
		// 从首页进入
		switch (l.homeurl) {
			case '1':
				info = fixeds('online')
				info.value = 1
				data.machines.online = 1
				break;
			case '2':
				info = fixeds('online')
				info.value = 2
				data.machines.online = 2
				break;
			case '3':
				info = fixeds('status')
				info.value = 3
				data.machines.status = 3
				break;
			case '4':
				info = fixeds('status')
				info.value = 2
				data.machines.status = 2
				break;
		}
	}
	getmachines()
}

// 查询列表
let getmachines = () => {
	data.mtloading = true
	getmachineList(data.machines).then(res => {
		data.mtloading = false
		if (res.state == 200) {
			data.list = res.data.data
			data.total = res.data.total
		}
	}).catch(err => {
		data.mtloading = false
		unAuth.value = $t('public.notPermis')
	})
}

// 获取设备分组
let gettypearr = () => {
	getgroupList().then(res => {
		if (res.state == 200) {
			let info = fixeds('machine_group_id')
			for (let item of res.data) {
				info.select.push({
					label: item.mg_id + '-' + item.mg_name,
					value: item.mg_id
				})
			}
		}
	})
}


// 查询回调
let inves = (e) => {
	data.machines = {}
	for (let key in e) {
		if (e[key] != '') {
			data.machines[key] = e[key]
		}
	}
	data.machines.machine_group_id = e.machine_group_id[e.machine_group_id.length - 1]
	data.machines.page = 1
	data.machines.pageNum = 15
	getmachines()
}

// 页数回调
let current = (e) => {
	data.machines.page = e
	getmachines()
}

// 条数回调
let fraction = (e) => {
	data.machines.pageNum = e
	getmachines()
}

// 添加设备
let add = (e) => {
	router.push({ path: '/machine/info/add_info' })
}

// 修改设备状态
let onstatus = (e) => {
	let status = {
		m_id: e.m_id
	}
	if (e.status == 1) {
		status.status = 2
	} else {
		status.status = 1
	}
	updatemachine(status).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.modifySuccess'),
				type: 'success'
			})
			getmachines()
			return
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	})
}

// 删除设备
let onmacbtn = (e) => {
	ElMessageBox.confirm($t('message.delDevice'))
		.then(res => {
			delmachine({ m_id: e.m_id }).then(res => {
				if (res.state == 200) {
					ElMessage({
						message: $t('message.delSuccess'),
						type: 'success'
					})
					getmachines()
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			})
		}).catch(err => {
			console.log('取消')
		})
}

let fixeds = (e) => {
	let info = ''
	data.lookup.map((item, index) => {
		if (item.key == e) {
			info = item
		}
	})
	return info
}

gethomeurl()

</script>
<style lang="scss" scoped>
.btn {
	.el-select {
		width: 180px !important;
	}

	.el-button {
		height: 32px !important;
	}

}
</style>
